<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <script>

    let array = [1, [1, 2], [1, 2, 3], [4]];

    // 方法一
    function flat(arr) {
      let res = [];
      function arrflat(arr) {
        for (let i of arr) {
          if (Array.isArray(i)) {
            arrflat(i);
          } else {
            res.push(i);
          }
        }
      }
      arrflat(arr)
      return res
    }
    const res = flat(array);
    console.log(res); //[1, 1, 2, 1, 2, 3,4]

    //  模拟 Array.prototype.flat 实现，默认展开一层，可传递参数用以展开多层

    //方法二
    function flatten(arr, depth) {
      if (depth === 0) return arr
      return arr.reduce((array, cur) => {
        return array.concat(Array.isArray(cur) ? flatten(cur, depth - 1) : cur)
      }, [])
    }
    //     // [1, 2, 3, 4, [5, 6]]
    console.log(flatten([1, 2, 3, [4, [5, 6]]]))
    //     // [1, 2, 3, 4, 5, 6]
    console.log(flatten([1, 2, 3, [4, [5, 6]]], 1))
  </script>
</body>

</html>